<?php

namespace App\V3\V3_2_7\Models;

use DateTimeInterface;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class TallyModel extends Model
{


    use HasFactory;

    protected $table = 'tally';

    protected $dateFormat = 'U';//这个时间字段被为被格式化为UNIX 时间戳的形式存储

    //toArray 时间转换问题
    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    /**
     * $dates 数组内的列转换为日期格式
     * @var array
     */
    protected $dates = [
        'add_time'
    ];

    //今日记账收入和支付金额
    static public function getTodayTallyImcome($condition, $type, $startTime, $endTime)
    {
        $info = self::select(DB::raw('SUM(money) as today_money'))
            ->where($condition)
            ->where('type', $type)
            ->whereBetween('created_at', [$startTime, $endTime])
            ->first();
        if (!empty($info['today_money'])) {
            return $info['today_money'];
        } else {
            return 0;
        }
    }

    //今日记账收入和支付金额去除销售金额
    static public function getTodayTallyImcomeDelSellData($condition, $type, $startTime, $endTime)
    {
        return self::select(
            DB::raw('SUM(money) as today_money'),
            DB::raw('count(*) as total_income_count'),
        )
            ->where('tally_class_id', '!=', 0)
            ->where('tally_class_name', '!=', '销售')
            ->where($condition)
            ->where('type', $type)
            ->whereBetween('created_at', [$startTime, $endTime])
            ->first();

    }

    //今日记账收入和支付金额去除采购金额
    static public function getTodayTallyImcomeDelPurchaseData($condition, $type, $startTime, $endTime)
    {
        return self::select(
            DB::raw('SUM(money) as today_money'),
            DB::raw('count(*) as total_expend_count'),
        )
            ->where('tally_class_name', '!=', '采购')
            ->where($condition)
            ->where('type', $type)
            ->whereBetween('created_at', [$startTime, $endTime])
            ->first();
    }

    //今日记账收入和支付金额
    static public function getTodayTallyCount($condition, $startTime, $endTime)
    {
        return self::where($condition)
            ->whereBetween('created_at', [$startTime, $endTime])
            ->count();
    }

}
